package com.examples

import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.example.zjx8969.myapplication.App
import com.example.zjx8969.myapplication.BuildConfig
import java.util.*
import kotlin.collections.ArrayList

class PermissionRequestFragment : Fragment() {
    var requestCode: Int = -1
    lateinit var permissions: Array<out String>
    private var onSuccessListener: ((Unit) -> Unit)? = null
    private var onFailureListener: ((List<String>) -> Unit)? = null
    private var manager: FragmentManager? = null
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        requestPermissions(permissions, requestCode)
        Log.d("tag", Env(10).getBaseString())
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode != this.requestCode) return
        val deniedList = ArrayList<String>(grantResults.size)
        grantResults.forEachIndexed { index, i ->
            if (i == PackageManager.PERMISSION_DENIED) {
                deniedList.add(permissions[index])
            }
        }
        if (deniedList.isEmpty()) {
            //all success
            onSuccessListener?.invoke(Unit)
        } else {
            //denied one at least
            onFailureListener?.invoke(deniedList)
        }
        manager?.beginTransaction()?.remove(this)?.commitAllowingStateLoss()
    }


    fun onSuccess(action: ((Unit) -> Unit)): PermissionRequestFragment {
        onSuccessListener = action
        return this
    }

    fun onFailure(action: (List<String>) -> Unit): PermissionRequestFragment {
        onFailureListener = action
        return this
    }

    fun request(fragmentManager: FragmentManager) {
        this.manager = fragmentManager
        val deniedList = ArrayList<String>(permissions.size)
        permissions.forEach { s ->
            if (ContextCompat.checkSelfPermission(App.getInstance(), s) == PackageManager.PERMISSION_DENIED) {
                deniedList.add(s)
            }
        }
        if (deniedList.isEmpty()) onSuccessListener?.invoke(Unit)
        else
            fragmentManager.beginTransaction().add(this, "PermissionRequestFragment$requestCode").commitAllowingStateLoss()
    }

    companion object {
        @JvmStatic
        private var staticRequestCode = 0
            get() {
                ++field
                field = if (field > 65535) 0 else field
                return field
            }


        @JvmStatic
        fun getInstance(vararg permission: String/*permission: Array<String>*/): PermissionRequestFragment {
            val activityResultFragment = PermissionRequestFragment()
            activityResultFragment.permissions = permission
            activityResultFragment.requestCode = staticRequestCode

            return activityResultFragment
        }
    }
}

class Env constructor(apiCode: Int) {
    private val baseParameter = """{"code":${apiCode},"clientOs":"aphone","osVersion":"${Build.VERSION.RELEASE}","appKey":"Perfect365_Explore_H5","clientVersion":"1.0","country":"${Locale.getDefault().country}","language":"${Locale.getDefault().language}","imei":"${getAndroidId()}","model":"${Build.MODEL}","channel":"${BuildConfig.FLAVOR}","userTags":"10""""
    private val userExtra = """ ,"userId":{0,number,#},"token":"{1}" """
    private val identifierExtra = """ ,"identifier":"{0}","value":"{1}" """
    private val ends = "}"

    private fun getAndroidId(): String {
        return Settings.Secure.getString(App.getInstance().contentResolver, Settings.Secure.ANDROID_ID)
    }

    fun getBaseString() = baseParameter + ends
}